package com.smalls.newvideotwo.mvp.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author thearyong
 * @date 2017/3/30
 */

public class Result {
    public JsonElement data;

    public static <T> T getResult(String response, Class<T> clazz) {
        return new Gson().fromJson(response, clazz);
    }

    /**
     * 形如：
     * "data":[
     * {"key1":"value"},
     * {"key2":"value"}
     * {"key3":"value"}
     * ]
     */
    public <M> List<M> getDataList(Class<M[]> clazz) {
        return getDataList(data, clazz);
    }

    public static <N> List<N> getDataList(JsonElement jsonElement, Class<N[]> clazz) {
//        Type type = new TypeToken<ArrayList<N>>() {}.getType();
        Gson gson = new Gson();
        N[] array = gson.fromJson(jsonElement, clazz);
        return Arrays.asList(array);
    }

    /**
     * 形如：
     * "data":{
     * "key1":"value",
     * "key2":"value",
     * }
     */
    public <M> M getDataObj(Class<M> clazz) {
        Gson gson = new Gson();
        return gson.fromJson(data, clazz);
    }

    /**
     * 形如：
     * "data":{
     * "key1":{value}
     * }
     */
    public <M> M getDataObjByKey(String key, Class<M> clazz) {
        Gson gson = new Gson();
        JsonElement value = data.getAsJsonObject().get(key);
        return gson.fromJson(value, clazz);
    }

    public static List<Map<String,String>> getDataStringToMap(JsonArray strJson) {
        if(strJson==null)
            return null;
        Gson gson2 = new GsonBuilder().enableComplexMapKeySerialization().create();
        Gson gson = new Gson();
        String jsonString = gson.toJson(strJson);
        Type type = new TypeToken<List<Map<String, String>>>() {}.getType();
        Log.i("getDataStringToMap","jsonString="+jsonString);
        List<Map<String,String>> map2 = gson2.fromJson(jsonString, type);
        return map2;
    }
}
